import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { Static, Type } from "@sinclair/typebox";
import moment from "moment";
import { Op } from "sequelize";
import { EmailCode } from "@db";
import { config } from "@config";

//Подробнее о возможностях валидации лучше смотреть тут - https://github.com/sinclairzx81/typebox
const verifyData = Type.Object({
    code: Type.String(),
});

async function verifyHandler(req: FastifyRequest, res: FastifyReply) {
    console.log(req.student);
    const { code } = (req.params || req.body) as {
        code: string;
    };

    const emailCode = await EmailCode.findOne({
        where: {
            email: req.student.email,
            code: code,
            createdAt: {
                [Op.gte]: moment().subtract(15, "minutes"),
            },
        },
    });
    if (!emailCode)
        return res.status(409).send({
            code: "INVALID_CODE",
            message: "Вы ввели неправильный код",
        });

    await req.student.update({
        isVerified: true,
    });
    if (req.method === "GET")
        return res.redirect(
            `https://${config.frontHost}/profile/student/${req.student.id}`
        );
    return res.send({
        code: "SUCCESS_VERIFED",
        message: "Аккаунт успешно верифицирован",
    });
}

export const verify = async (fastify: FastifyInstance) => {
    fastify.get<{
        Querystring: Static<typeof verifyData>;
    }>(
        "/student/verify/:code",
        {
            preHandler: fastify.auth("student", false),
            schema: {
                tags: ["student"],
                params: verifyData,
            },
        },
        verifyHandler
    );
    fastify.post<{
        Body: Static<typeof verifyData>;
    }>(
        "/student/verify",
        {
            preHandler: fastify.auth("student", false),
            schema: {
                tags: ["student"],
                body: verifyData,
            },
        },
        verifyHandler
    );
};
